package com.xoa.service.book;

import com.xoa.dao.book.BookInfoMapper;
import com.xoa.dao.book.BookManageMapper;
import com.xoa.dao.book.BookTypeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.users.UserPrivMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.book.BookInfoWithBLOBs;
import com.xoa.model.book.BookManager;
import com.xoa.model.users.UserPriv;
import com.xoa.model.users.Users;
import com.xoa.util.*;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebEndpoint;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

import static com.xoa.util.FileUploadUtil.allowUpload;


/**
 * 创建作者:   牛江丽
 * 创建日期:   2017年10月23日 下午14:43:00
 * 类介绍  :图书信息service
 * 构造参数:
 */
@Service
public class BookInfoService {

    @Resource
    private BookInfoMapper bookInfoMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private BookTypeMapper bookTypeMapper;

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private UserPrivMapper userPrivMapper;

    @Resource
    private BookManageMapper bookManageMapper;

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年10月23日 下午16:32:00
     * 方法介绍:   添加图书信息
     * 参数说明:   @param bookInfoWithBLOBs
     * 返回值说明:
     */
    @Transactional
    public ToJson<BookInfoWithBLOBs> insertBookInfo(BookInfoWithBLOBs bookInfoWithBLOBs,MultipartFile imageFile,HttpServletRequest request){
        ToJson<BookInfoWithBLOBs> json = new ToJson<BookInfoWithBLOBs>(1, "error");
        try{
            //图片的添加，注：必须写在id后
            int imgResult=uploadImg(request,bookInfoWithBLOBs,imageFile);
            if(imgResult!=0){
                json.setMsg("图片格式不正确！");
                return json;
            }
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
            bookInfoWithBLOBs.setBorrPerson(user.getUserId());
            int count=bookInfoMapper.insertBookInfo(bookInfoWithBLOBs);
            if(count>0){
                json.setMsg("ok");
                json.setFlag(0);
            }
        }catch(Exception e){
            json.setMsg(e.getMessage());
            L.e("BookInfoService insertBookInfo:"+e);
            e.printStackTrace();
        }
        return  json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年10月23日 下午15:46:00
     * 方法介绍:   根据id修改图书信息
     * 参数说明:   @param bookInfoWithBLOBs
     * 返回值说明:
     */
    @Transactional
    public ToJson<BookInfoWithBLOBs> upBookInfoById(BookInfoWithBLOBs bookInfoWithBLOBs,MultipartFile imageFile,HttpServletRequest request){
        ToJson<BookInfoWithBLOBs> json = new ToJson<BookInfoWithBLOBs>(1, "error");
        try{
            //图片的添加，注：必须写在id后
            int imgResult=uploadImg(request,bookInfoWithBLOBs,imageFile);
            if(imgResult!=0){
                json.setMsg("img");
                return json;
            }
            int count=bookInfoMapper.upBookInfoById(bookInfoWithBLOBs);
            if(count>0){
                json.setMsg("ok");
                json.setFlag(0);
            }
        }catch(Exception e){
            /*json.setMsg(e.getMessage());*/
            L.e("BookInfoService upBookInfoById:"+e);
            e.printStackTrace();
        }
        return  json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年10月23日 下午15:46:00
     * 方法介绍:   根据id删除图书信息
     * 参数说明:   @param bookId
     * 返回值说明:
     */
    @Transactional
    public ToJson<BookInfoWithBLOBs> delBookInfoById(Integer bookId){
        ToJson<BookInfoWithBLOBs> json = new ToJson<BookInfoWithBLOBs>(1, "error");
        try{
            int count=bookInfoMapper.delBookInfoById(bookId);
            if(count>0){
                json.setMsg("ok");
                json.setFlag(0);
            }
        }catch(Exception e){
            json.setMsg(e.getMessage());
            L.e("BookInfoService delBookInfoById:"+e);
            e.printStackTrace();
        }
        return  json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年10月23日 下午15:46:00
     * 方法介绍:   根据id查询图书信息
     * 参数说明:   @param bookId
     * 返回值说明:
     */
    @SuppressWarnings("all")
    public ToJson<BookInfoWithBLOBs> selBookInfoById(Integer bookId){
        ToJson<BookInfoWithBLOBs> json = new ToJson<BookInfoWithBLOBs>(1, "error");
        try{
            BookInfoWithBLOBs bookInfoWithBLOBs=bookInfoMapper.selBookInfoById(bookId);
            bookInfoWithBLOBs.setBorrowNum(bookManageMapper.selCountManageByBookNo(bookInfoWithBLOBs.getBookNo()));
            if(!StringUtils.checkNull(bookInfoWithBLOBs.getOpen())){
                String deptStr="";
                String userStr="";
                String userPrivStr="";
                String[] openArr=bookInfoWithBLOBs.getOpen().split(";");
                for(int i=0;i<openArr.length;i++){
                    switch (i){
                        case 0:
                            if(!StringUtils.checkNull(openArr[i])){
                                String[] deptOpenArr=openArr[i].split(",");
                                for(int j=0;j<deptOpenArr.length;j++){
                                    if(!StringUtils.checkNull(departmentMapper.getDeptNameByDeptId(Integer.valueOf(deptOpenArr[j])))){
                                        deptStr+=departmentMapper.getDeptNameByDeptId(Integer.valueOf(deptOpenArr[j]))+",";
                                    }
                                }
                            }
                            break;
                        case 1:
                            if(!StringUtils.checkNull(openArr[i])){
                                String[] userOpenArr=openArr[i].split(",");
                                for(int j=0;j<userOpenArr.length;j++){
                                    if(!StringUtils.checkNull(usersMapper.getUsernameByUserId(userOpenArr[j]))){
                                        userStr+=usersMapper.getUsernameByUserId(userOpenArr[j])+",";
                                    }
                                }
                            }
                            break;
                        case 2:
                            if(!StringUtils.checkNull(openArr[i])){
                                String[] userPrivOpenArr=openArr[i].split(",");
                                for(int j=0;j<userPrivOpenArr.length;j++){
                                    if(!StringUtils.checkNull(userPrivMapper.getPrivNameById(Integer.valueOf(userPrivOpenArr[j])))){
                                        userPrivStr+=userPrivMapper.getPrivNameById(Integer.valueOf(userPrivOpenArr[j]))+",";
                                    }
                                }
                            }
                            break;
                    }
                }
                bookInfoWithBLOBs.setOpenName(deptStr+";"+userStr+";"+userPrivStr);
            }
            json.setObject(bookInfoWithBLOBs);
            json.setMsg("ok");
            json.setFlag(0);
        }catch(Exception e){
            json.setMsg(e.getMessage());
            L.e("BookInfoService selBookInfoById:"+e);
            e.printStackTrace();
        }
        return  json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年10月23日 下午15:46:00
     * 方法介绍:   查询所有图书信息
     * 参数说明:   @param autoId
     * 返回值说明:
     */
    public ToJson<BookInfoWithBLOBs> selBookInfoByCond(BookInfoWithBLOBs bookInfoWithBLOBs,Integer page,Integer pageSize,boolean useFlag){
        ToJson<BookInfoWithBLOBs> json = new ToJson<BookInfoWithBLOBs>(1, "error");
        try{
            //分页
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            map.put("bookInfoWithBLOBs",bookInfoWithBLOBs);
            List<BookInfoWithBLOBs> list=bookInfoMapper.selBookInfoByCond(map);
            for(BookInfoWithBLOBs bookInfo:list){
                bookInfo.setBorrowNum(bookManageMapper.selCountManageByBookNo(bookInfo.getBookNo()));
                if(!StringUtils.checkNull(bookInfo.getOpen())){
                    String deptStr="";
                    String userStr="";
                    String userPrivStr="";
                    String[] openArr=bookInfo.getOpen().split(";");
                    for(int i=0;i<openArr.length;i++){
                        switch (i){
                            case 0:
                                  if(!StringUtils.checkNull(openArr[i])){
                                      String[] deptOpenArr=openArr[i].split(",");
                                      for(int j=0;j<deptOpenArr.length;j++){
                                          if(!StringUtils.checkNull(departmentMapper.getDeptNameByDeptId(Integer.valueOf(deptOpenArr[j])))){
                                              deptStr+=departmentMapper.getDeptNameByDeptId(Integer.valueOf(deptOpenArr[j]))+",";
                                          }
                                      }
                                  }
                                break;
                            case 1:
                               if(!StringUtils.checkNull(openArr[i])){
                                   String[] userOpenArr=openArr[i].split(",");
                                   for(int j=0;j<userOpenArr.length;j++){
                                       if(!StringUtils.checkNull(usersMapper.getUsernameByUserId(userOpenArr[j]))){
                                           userStr+=usersMapper.getUsernameByUserId(userOpenArr[j])+",";
                                       }
                                   }
                               }
                                break;
                            case 2:
                                if(!StringUtils.checkNull(openArr[i])){
                                    String[] userPrivOpenArr=openArr[i].split(",");
                                    for(int j=0;j<userPrivOpenArr.length;j++){
                                        if(!StringUtils.checkNull(userPrivMapper.getPrivNameById(Integer.valueOf(userPrivOpenArr[j])))){
                                            userPrivStr+=userPrivMapper.getPrivNameById(Integer.valueOf(userPrivOpenArr[j]))+",";
                                        }
                                    }
                                }
                                break;
                        }
                    }
                    bookInfo.setOpenName(deptStr+";"+userStr+";"+userPrivStr);
                }
            }
            json.setTotleNum(bookInfoMapper.selBookInfoCountByCond(bookInfoWithBLOBs));
            json.setObj(list);
            json.setMsg("ok");
            json.setFlag(0);
        }catch(Exception e){
            json.setMsg(e.getMessage());
            L.e("BookInfoService selBookInfoByCond:"+e);
            e.printStackTrace();
        }
        return  json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年10月23日 下午18:12:00
     * 方法介绍:   图书信息导入
     * 参数说明:   @param
     * 返回值说明:
     */
    @Transactional
    public  ToJson<BookInfoWithBLOBs> importBookInfo(HttpServletRequest request, HttpServletResponse response, MultipartFile file, HttpSession session) {
        ToJson<BookInfoWithBLOBs> json = new ToJson<BookInfoWithBLOBs>(1, "error");
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
                 StringBuffer buffer=new StringBuffer();
        if(osName.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                path = path.append(str2 + "/xoa");
            }
            path.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            path=path.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString();
                    uuid = uuid.replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    //将文件上传成功后进行读取文件
                    //进行读取的路径
                    String readPath = path.append(newFileName).toString();
                    InputStream in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row rowObj = null;
                    int lastRowNum = sheetObj.getLastRowNum();
                    int inputFail=0;
                    int inputSuccess=0;
                    String faillReason="";
                    for (int temp = 2; temp <= lastRowNum; temp++) {
                        rowObj = sheetObj.getRow(temp);
                        if (rowObj != null) {
                            Cell c0 = rowObj.getCell(0);
                            Cell c1 = rowObj.getCell(1);
                            Cell c2 = rowObj.getCell(2);
                            Cell c3 = rowObj.getCell(3);
                            Cell c4 = rowObj.getCell(4);
                            Cell c5 = rowObj.getCell(5);
                            Cell c6 = rowObj.getCell(6);
                            Cell c7 = rowObj.getCell(7);
                            Cell c8 = rowObj.getCell(8);
                            Cell c9 = rowObj.getCell(9);
                            Cell c10 = rowObj.getCell(10);
                            Cell c11 = rowObj.getCell(11);
                            Cell c12 = rowObj.getCell(12);
                            Cell c13 = rowObj.getCell(13);
                            Cell c14 = rowObj.getCell(14);
                            if (c0.getStringCellValue() != "" && c1.getStringCellValue()!= "" && c3.getStringCellValue() != ""  && c12.getStringCellValue() != "" && c9.getNumericCellValue() != -1) {
                                BookInfoWithBLOBs bookInfoWithBLOBs = new BookInfoWithBLOBs();
                                bookInfoWithBLOBs.setDept(Integer.valueOf(departmentMapper.getDeptIdByDeptName(c0.getStringCellValue()).size()>0?departmentMapper.getDeptIdByDeptName(c0.getStringCellValue()).get(0):""));
                                bookInfoWithBLOBs.setBookName(c1.getStringCellValue());
                                bookInfoWithBLOBs.setAuthor(c2.getStringCellValue());
                                bookInfoWithBLOBs.setBookNo(c3.getStringCellValue());
                                if(bookInfoMapper.selInfoByBookNo(c3.getStringCellValue())==null){
                                    json.setMsg("图书编号不能重复");
                                    return json;
                                }
                                bookInfoWithBLOBs.setTypeId(bookTypeMapper.selIdByName(c4.getStringCellValue()));
                                bookInfoWithBLOBs.setIsbn(c5.getStringCellValue());
                                bookInfoWithBLOBs.setPubHouse(c6.getStringCellValue());
                                bookInfoWithBLOBs.setPubDate(DateFormat.getStrDate(c7.getDateCellValue()));
                                bookInfoWithBLOBs.setArea(c8.getStringCellValue());
                                bookInfoWithBLOBs.setAmt((int)c9.getNumericCellValue());
                                bookInfoWithBLOBs.setPrice(BigDecimal.valueOf(c10.getNumericCellValue()));
                                bookInfoWithBLOBs.setBrief(c11.getStringCellValue());
                                String arrange = c12.getStringCellValue();//借阅范围（包括部门、用户、角色）
                                String[] arrangArr = arrange.split(";");
                                StringBuffer str = new StringBuffer();
                                for(int i=0;i<arrangArr.length;i++) {
                                    switch (i) {
                                        case 0:
                                            if (!StringUtils.checkNull(arrangArr[i])) {
                                                String[] deptOpenArr = arrangArr[i].split(",");
                                                for (int j = 0; j < deptOpenArr.length; j++) {
                                                    if (departmentMapper.getDeptIdByDeptName(deptOpenArr[j]).size()>0) {
                                                        List<String> nameList=departmentMapper.getDeptIdByDeptName(deptOpenArr[j]);
                                                        String name="";
                                                        if(nameList.size()>0){
                                                            name=nameList.get(0);
                                                        }
                                                        str.append(name+",");
                                                    }
                                                }
                                            }
                                            str.append(";");
                                            break;
                                        case 1:
                                            if (!StringUtils.checkNull(arrangArr[i])) {
                                                String[] userOpenArr = arrangArr[i].split(",");
                                                for (int j = 0; j < userOpenArr.length; j++) {
                                                    Users users = usersMapper.getUserByUserName(userOpenArr[j]);
                                                    if (users != null) {
                                                        if (!StringUtils.checkNull(users.getUserName())) {
                                                            str.append(users.getUserName()+",");
                                                        }
                                                    }
                                                }
                                            }
                                            str.append(";");
                                            break;
                                        case 2:
                                            if (!StringUtils.checkNull(arrangArr[i])) {
                                                String[] userPrivOpenArr = arrangArr[i].split(",");
                                                for (int j = 0; j < userPrivOpenArr.length; j++) {
                                                    UserPriv userPriv = userPrivMapper.getUserPrivByName(userPrivOpenArr[j]);
                                                    if (userPriv != null) {
                                                        if (!StringUtils.checkNull(userPriv.getPrivName())) {
                                                            str.append(userPriv.getUserPriv()+",");
                                                        }
                                                    }
                                                }
                                            }
                                            break;
                                    }
                                }
                                bookInfoWithBLOBs.setOpen(str.toString());
                                if (usersMapper.getUserByUserName(c13.getStringCellValue()) != null) {
                                    bookInfoWithBLOBs.setBorrPerson(usersMapper.getUserByUserName(c13.getStringCellValue()).getUserId());
                                }
                                bookInfoWithBLOBs.setMemo(c14.getStringCellValue());
                            }
                        }
                    }
                    json.setFlag(0);
                    json.setMsg("ok");
                    dest.delete();
                } else {
                    json.setMsg("0");//文件类型不正确
                    return json;
                }
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("BookInfoService importBookInfo:"+e);
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年10月24日 上午9:43:00
     * 方法介绍:   导出查询出的图书信息
     * 参数说明:   @param autoId
     * 返回值说明:
     */
    public ToJson<BookInfoWithBLOBs> outputSelBookInfoByCond(BookInfoWithBLOBs bookInfoWithBLOBs,HttpServletRequest request, HttpServletResponse response){
        ToJson<BookInfoWithBLOBs> json = new ToJson<BookInfoWithBLOBs>(1, "error");
        try{
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("bookInfoWithBLOBs",bookInfoWithBLOBs);
            List<BookInfoWithBLOBs> list=bookInfoMapper.selBookInfoByCond(map);
            for(BookInfoWithBLOBs bookInfo:list){
                bookInfo.setBorrowNum(bookManageMapper.selCountManageByBookNo(bookInfo.getBookNo()));
                bookInfo.setBorrowCond("已借出"+bookInfo.getBorrowNum()+"册，剩余"+bookInfo.getAmt()+"册");
                if(!StringUtils.checkNull(bookInfo.getOpen())){
                    String deptStr="";
                    String userStr="";
                    String userPrivStr="";
                    String[] openArr=bookInfo.getOpen().split(";");
                    for(int i=0;i<openArr.length;i++){
                        switch (i){
                            case 0:
                                if(!StringUtils.checkNull(openArr[i])){
                                    String[] deptOpenArr=openArr[i].split(",");
                                    for(int j=0;j<deptOpenArr.length;j++){
                                        if(!StringUtils.checkNull(departmentMapper.getDeptNameByDeptId(Integer.valueOf(deptOpenArr[j])))){
                                            deptStr+=departmentMapper.getDeptNameByDeptId(Integer.valueOf(deptOpenArr[j]))+",";
                                        }
                                    }
                                }
                                break;
                            case 1:
                                if(!StringUtils.checkNull(openArr[i])){
                                    String[] userOpenArr=openArr[i].split(",");
                                    for(int j=0;j<userOpenArr.length;j++){
                                        if(!StringUtils.checkNull(usersMapper.getUsernameByUserId(userOpenArr[j]))){
                                            userStr+=usersMapper.getUsernameByUserId(userOpenArr[j])+",";
                                        }
                                    }
                                }
                                break;
                            case 2:
                                if(!StringUtils.checkNull(openArr[i])){
                                    String[] userPrivOpenArr=openArr[i].split(",");
                                    for(int j=0;j<userPrivOpenArr.length;j++){
                                        if(!StringUtils.checkNull(userPrivMapper.getPrivNameById(Integer.valueOf(userPrivOpenArr[j])))){
                                            userPrivStr+=userPrivMapper.getPrivNameById(Integer.valueOf(userPrivOpenArr[j]))+",";
                                        }
                                    }
                                }
                                break;
                        }
                    }
                    bookInfo.setOpenName(deptStr+";"+userStr+";"+userPrivStr);
                }
            }
            HSSFWorkbook tableWork = ExcelUtil.makeExcelHead("图书信息导出", 16);
            String[] secondTitles = {"部门", "书名","作者","图书编号","图书类别","ISBN号","出版社","出版日期","存放地点","数量","价格","内容简介","借阅情况","借阅范围","录入人","备注"};
            HSSFWorkbook excelWork = ExcelUtil.makeSecondHead(tableWork, secondTitles);
            String[] beanProperty = {"deptName","bookName","author","bookNo","typeName","isbn","pubHouse","pubDate","area","amt","price","brief","borrowCond","openName","borrPersonName","memo"};
            HSSFWorkbook workbook = ExcelUtil.exportExcelData(excelWork, list, beanProperty);
            response.setContentType("text/html;charset=UTF-8");
            OutputStream out = response.getOutputStream();

            String filename = "图书信息导出.xls"; //考虑多语言
            filename = FileUtils.encodeDownloadFilename(filename,
                    request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition",
                    "attachment;filename=" + filename);
            workbook.write(out);
            out.flush();
            out.close();
            json.setObj(list);
            json.setMsg("ok");
            json.setFlag(0);
        }catch(Exception e){
            json.setMsg(e.getMessage());
            L.e("BookInfoService outputSelBookInfoByCond:"+e);
            e.printStackTrace();
        }
        return  json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017-10-25 10:33
     * 类介绍  :   批量删除图书信息
     * 构造参数:
     */
    public ToJson<BookInfoWithBLOBs> delBookInfoByIds(String[] bookIds){
        ToJson<BookInfoWithBLOBs> json = new ToJson<BookInfoWithBLOBs>(1, "error");
        try {
            int count=bookInfoMapper.delBookInfoByIds(bookIds);
            if(count>0){
                json.setFlag(0);
                json.setMsg("ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年10月23日 下午15:46:00
     * 方法介绍:   根据bookNo条件查询图书信息条数
     * 参数说明:   @param bookInfoWithBLOBs
     * 返回值说明:
     */
    public ToJson<BookInfoWithBLOBs> selInfoCountByBookNo(String bookNo){
        ToJson<BookInfoWithBLOBs> json = new ToJson<BookInfoWithBLOBs>(1, "error");
        try {
            BookInfoWithBLOBs bookInfoWithBLOBs=bookInfoMapper.selInfoByBookNo(bookNo);
            if(bookInfoWithBLOBs!=null){
                json.setTotleNum(1);
            }else{
                json.setTotleNum(0);
            }
            json.setFlag(0);
            json.setMsg("ok");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 图片上传
     * @param request
     * @param imageFile
     */
    public int uploadImg(HttpServletRequest request,BookInfoWithBLOBs bookInfoWithBLOBs, MultipartFile imageFile){
        int resultFlag=0;
        try{
            //图片进行处理
            if(imageFile!=null){
                String imageType=imageFile.getContentType();
                boolean b = allowUpload(imageType);
                if (!b){
                    resultFlag=1;//图片格式不正确
                }
            }
            String realPath = request.getSession().getServletContext().getRealPath("/");
            String resourcePath = "ui/img/book/info";
            //先查询是否已经上传了该图片，如果上传了删除后再上传，否则直接上传
            BookInfoWithBLOBs temp=bookInfoMapper.selBookInfoById(bookInfoWithBLOBs.getBookId());
            if(temp!=null){
                if (!StringUtils.checkNull(temp.getAttachmentId())) {//图书封面图片
                    File temp1 = new File(realPath + resourcePath + temp.getAttachmentId());
                    if (temp1.exists()) {
                        temp1.delete();
                    }
                }
            }
            //上传图片并进行修改数据库数据
            if (imageFile != null) {
                if (allowUpload(imageFile.getContentType())) {
                    String fileName = FileUploadUtil.rename(imageFile.getOriginalFilename());
                    File dir = new File(realPath + resourcePath);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    File file = new File(dir, fileName);
                    imageFile.transferTo(file);
                    bookInfoWithBLOBs.setAttachmentId(fileName);
                    bookInfoWithBLOBs.setAttachmentName("");
                }
            }else{
                bookInfoWithBLOBs.setAttachmentId("");
                bookInfoWithBLOBs.setAttachmentName("");
            }
        }catch (Exception e){
            L.e("BookInfoService uploadImg:"+e);
            e.printStackTrace();
        }
        return resultFlag;
    }
}
